package cn.jbooter.repository.autoconfigure.second;

import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;


/**
 * 第二数据源配置
 * @author HeJian
 *
 */
@Configuration
@AutoConfigureBefore(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(prefix="spring.datasource.druid.second",name="enabled",havingValue="true")
@EnableTransactionManagement
public class SecondDataSourceConfigure {
	private static final Logger logger = LoggerFactory.getLogger(SecondDataSourceConfigure.class);
	
	@Bean(initMethod="init",destroyMethod="close")
	@ConfigurationProperties("spring.datasource.druid.second")
	public DataSource secondDataSource(){
		DruidDataSource build = DruidDataSourceBuilder.create().build();
		logger.info("===>>>第2数据源初始化完成.");
	    return build;
	}
	
	@Bean
    public JdbcTemplate secondJdbcTemplate(){
        return new JdbcTemplate(secondDataSource());
    }
	
	/**
     * 使用jdbc编程式事物管理
     * @return
     */
    @Bean
    public TransactionTemplate secondTransactionTemplate(){
        return new TransactionTemplate(secondTransactionManager());
    }
	
    /**
	 * 第2数据源事务配置
	 */
	@Bean
	public PlatformTransactionManager secondTransactionManager() {
		return new DataSourceTransactionManager(secondDataSource());
	}

	
}
